package com.czwj.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.LiteDeviceResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class SessionTimeoutInterceptor implements HandlerInterceptor {

	private static final Logger log = LoggerFactory.getLogger(SessionTimeoutInterceptor.class);

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
//		log.info("---------------------开始进入请求地址拦截----------------------------");
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mav)
			throws Exception {
//		log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
//		log.info("自定义拦截器");
		HttpSession session = request.getSession(true);
		Object obj = session.getAttribute("userInfo");
		String type = request.getHeader("X-Requested-With");
		if (obj == null) {
            // 重定向
            String path = request.getContextPath();
            String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";
            //response.sendRedirect(contextPath+"/index.jsp");
            // System.err.println("sendRedirect");
            // 转发
            if (type!=null && type.equals("XMLHttpRequest")) {
                // ajax请求
                response.setHeader("SESSIONSTATUS", "TIMEOUT");
                response.setHeader("CONTEXTPATH", basePath+"/");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);//403 禁止
                return false;
            } else {
            	response.setCharacterEncoding("utf-8");
    			response.setContentType("text/html; charset=utf-8");
    			PrintWriter out = response.getWriter();
    			
    			StringBuilder builder = new StringBuilder();
    			
    			LiteDeviceResolver deviceResolver = new LiteDeviceResolver();
    			Device device = deviceResolver.resolveDevice(request);
    			if (!device.isMobile()){
    				builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
    				builder.append("alert(\"页面过期，请重新登录\");");
    				builder.append("window.top.location.href='/construct/'");
        			builder.append("</script>");
    			}else{
    				builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
    				builder.append("alert(\"页面过期，请重新进入小程序\");");
    				builder.append("window.top.location.href='/construct/app/login.do'");
        			builder.append("</script>");
    			}
    			
    			out.print(builder.toString());
    			out.close();
    			return false;
            }
        }
		return true;
	}

}

